<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Cache;
use think\facade\Event;

class Product extends Base
{
    protected $name = 'product';

    public function cate1()
    {
        return $this->hasOne(ProductCate::class, 'id', 'cate_1')->field('id,title');
    }

    public function cate2()
    {
        return $this->hasOne(ProductCate::class, 'id', 'cate_2')->field('id,title');
    }

    public function p()
    {
        return $this->hasOne(Area::class, 'code', 'province')->field('code,province as title');
    }

    public function c()
    {
        return $this->hasOne(Area::class, 'code', 'city')->field('code,city as title');
    }

    public function d()
    {
        return $this->hasOne(Area::class, 'code', 'district')->field('code,district as title');
    }

    public function getTypeAttr($value, $type = 1)
    {
        if ($type == 1) {
            switch ($value) {
                case 1:
                    return '未跟进';
                case 2:
                    return '已跟进';
                default:
                    return '其他';
            }
        } else {
        return [1 => '未跟进', 2 => '已跟进'];
        }
    }

    public function getOrderStatusAttr($value)
    {
        switch ($value) {
            case 0:
                return '已接单';
            case 1:
                return '可接单';
            default:
                return '其他';
        }
    }

    public static function submit($param, $user): array
    {
        try {
            $all = [];

            $info = parent::where(['id' => $param['id'], 'is_del' => 0, 'status' => 1])->find();
            if (empty($info)) {
                return ['code' => -1, 'msg' => '商品不存在或已下架'];
            }
            if($user->is_active==2&&$info->cate_1==1)
            {
                return ['code' => -1, 'msg' => '不可重复购买'];
            }
            if($user->is_active==1&&$info->cate_1==2)
            {
                return ['code' => -1, 'msg' => '请先激活'];
            }
            if (!$info->vip_price || $info->vip_price <= 0) {
                return ['code' => -1, 'msg' => '商品价格错误'];
            }
            if ($info->num >= $info->stock) {
                return ['code' => -1, 'msg' => '库存不足'];
            }
            $all[] = [
                'pid' => $info->id,
                'num' => $param['num'],
                'cate_1' => $info->cate_1,
            ];
            Cache::set('tsOrder_' . $user->id, json_encode($all));

            return ['code' => 4, 'msg' => 'success', 'url' => url('order/index')->build()];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }


}
